package com.btkjgc.service.impl;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;

import com.btkjgc.models.AdminUser;
import com.btkjgc.models.AjaxObj;
import com.btkjgc.models.PackagePostage;
import com.btkjgc.models.PackagePostageDetail;
import com.btkjgc.models.extend.PackagePostageDetailModel;
import com.btkjgc.models.extend.PackagePostageModel;
import com.btkjgc.service.intf.PackageFareManageService_Intf;
import com.btkjgc.utils.HibernateUtil;

@Service
public class PackageFareManageService_Impl extends BaseService_Impl implements PackageFareManageService_Intf
{
	
	static Logger logger = Logger.getLogger(PackageFareManageService_Impl.class);

	@Override
	public void setListData(HttpServletRequest request, ModelAndView mv,int pageIndex, int totalRecord,
			List<PackagePostageModel> packagePostageList) {
		// TODO Auto-generated method stub
		
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements())
		{
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
		
		mv.addObject("package_postage_list",packagePostageList);
		
		mv.addObject("currentpage", pageIndex);
		mv.addObject("totalRecord", totalRecord);
		
	}
 


	@Override
	public AjaxObj insertPackageFareModel(
			PackagePostageModel packagePostageModel) {
		// TODO Auto-generated method stub
		
		AjaxObj ajaxObj=new AjaxObj();
		ajaxObj.setResult(true);
		
		try {
			//保存计费规则
			if(packagePostageModel.getAreaRadio()==1){
				packagePostageModel.setProvinceids(null);
				packagePostageModel.setCityids(null);
			}
			if(packagePostageModel.getBeginTimeRadio()==1){
				packagePostageModel.setBeginTime(null);
			}
			if(packagePostageModel.getEndTimeRadio()==1){
				packagePostageModel.setEndTime(null);
			}
			PackagePostage packagePostage  =new PackagePostage();
			PropertyUtils.copyProperties(packagePostage,packagePostageModel);
			packagePostage.setDel(0);
			packagePostage.setCreatedate(new Date());
			packagePostage.setStatus(1);
			packagePostage.setOperdate(new Date());
			packagePostage.setOperid(getLoginUser().getId());
			Integer key=HibernateUtil.save(packagePostage);
			
			
			//保存阶梯费用设置
			List<PackagePostageDetailModel> packagePostageDetailModelDetailList=packagePostageModel.getPackagePostageDetailModelDetailList();
			
			int count=packagePostageDetailModelDetailList.size();
			
			PackagePostageDetail  objs[]=new PackagePostageDetail[count];
			
			for (int i = 0; i <count; i++) {
				
				PackagePostageDetailModel packagePostageDetailModel = packagePostageDetailModelDetailList.get(i);
				packagePostageDetailModel.setConPostageid(key);
				if(packagePostageDetailModel.getMileage() != null){
					packagePostageDetailModel.setChargetype(1);
				}else{
					packagePostageDetailModel.setChargetype(2);
				}
				PackagePostageDetail packagePostageDetail  =new PackagePostageDetail();
				PropertyUtils.copyProperties(packagePostageDetail,packagePostageDetailModel);
	 
				packagePostageDetail.setSort(i+1);
				objs[i]=packagePostageDetail;
				
			}
			HibernateUtil.batchSave(objs);
			
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
			ajaxObj.setResult(false);
			ajaxObj.setMsg("添加时出错");
		}
		
		return ajaxObj;
	}

	@Override
	public AjaxObj updatePackagePostageModel(
			PackagePostageModel packagePostageModel) {
		// TODO Auto-generated method stub
		AjaxObj ajaxObj=new AjaxObj();
		ajaxObj.setResult(true);
		PackagePostage packagePostage=new PackagePostage();
		
		//手动控制事务批量提交
		Session session =HibernateUtil.openSession();
		Transaction tx  = session.beginTransaction();

		try {
			
			//更新套餐资费
			if(packagePostageModel.getAreaRadio()==1){
				session.createQuery("update from PackagePostage set provinceids=null where id="+packagePostageModel.getId()).executeUpdate();
				session.createQuery("update from PackagePostage set cityids=null where id="+packagePostageModel.getId()).executeUpdate();
				packagePostageModel.setProvinceids(null);
				packagePostageModel.setCityids(null);
			}
			if(packagePostageModel.getBeginTimeRadio()==1){
				session.createQuery("update from PackagePostage set begintime=null where id="+packagePostageModel.getId()).executeUpdate();
				packagePostageModel.setBeginTime(null);
			}
			if(packagePostageModel.getEndTimeRadio()==1){
				session.createQuery("update from PackagePostage set endtime=null where id="+packagePostageModel.getId()).executeUpdate();
				packagePostageModel.setEndTime(null);
			}
			
			if(packagePostageModel.getPublicCharge()==0){
				session.createQuery("update from PackagePostage set bill=null where id="+packagePostageModel.getId()).executeUpdate();
				packagePostageModel.setBill(null);
			}
		
			PropertyUtils.copyProperties(packagePostage, packagePostageModel);
			packagePostage.setOperdate(new Date());
			packagePostage.setOperid(getLoginUser().getId());
			Query query = session.createQuery(getUpdateHql(packagePostage));
			query.executeUpdate();
			   
			
			//更新阶梯费用设置
			List<PackagePostageDetailModel> list=packagePostageModel.getPackagePostageDetailModelDetailList();
			int count=list.size();
			
			PackagePostageDetail  objs[]=new PackagePostageDetail[count];
			
			for (int i = 0; i <count; i++) {
				
				PackagePostageDetailModel packagePostageDetailModel = list.get(i);
				packagePostageDetailModel.setConPostageid(packagePostageModel.getId());
				if(packagePostageDetailModel.getMileage() != null){
					packagePostageDetailModel.setChargetype(1);
				}else{
					packagePostageDetailModel.setChargetype(2);
				}
				PackagePostageDetail packagePostageDetail  =new PackagePostageDetail();
				PropertyUtils.copyProperties(packagePostageDetail,packagePostageDetailModel);
	 
				packagePostageDetail.setSort(i+1);
				objs[i]=packagePostageDetail;
				
			}
			
	
			
			session.flush();
			session.clear();
			String sql="delete from package_postage_detail_t where conPostageid= ?";
			query = session.createSQLQuery(sql);
			query.setInteger(0, packagePostageModel.getId());
		    query.executeUpdate();
 
		    
			for (int i = 0; i < objs.length; i++) {
				 session.save(objs[i]);
			}
			
			session.flush();
			session.clear();
			tx.commit();
 
			
		} catch (IllegalAccessException | InvocationTargetException
				| NoSuchMethodException e) {
			// TODO Auto-generated catch block
			ajaxObj.setResult(false);
			ajaxObj.setMsg("修改时出错");
			e.printStackTrace();
		}
		
		return ajaxObj;
	}

	@Override
	public void setEditdata(HttpServletRequest request, ModelAndView mv, Integer id) {
		// TODO Auto-generated method stub
		Enumeration<String> names = request.getParameterNames();
		while (names.hasMoreElements()) {
			String name = names.nextElement();
			mv.addObject(name, request.getParameter(name));
		}
		//设置套餐费用参数
		PackagePostageModel packagePostageModel=(PackagePostageModel) HibernateUtil.executeSQLQueryObject("select * from package_postage_t where id ="+id,PackagePostageModel.class);
		
		if(StringUtils.isEmpty(packagePostageModel.getBeginTime())){
			packagePostageModel.setBeginTimeRadio(1);
		}else {
			packagePostageModel.setBeginTimeRadio(2);
		}
		if(StringUtils.isEmpty(packagePostageModel.getEndTime())){
			packagePostageModel.setEndTimeRadio(1);
		}else {
			packagePostageModel.setEndTimeRadio(2);
		}
		
		if(StringUtils.isEmpty(packagePostageModel.getProvinceids())&&StringUtils.isEmpty(packagePostageModel.getCityids())){
			packagePostageModel.setAreaRadio(1);
		}else {
			packagePostageModel.setAreaRadio(2);
		}
		
		
			
		//设置阶梯费用参数
		List<PackagePostageDetailModel> packagePostageDetailModelDetailList;
		packagePostageDetailModelDetailList=HibernateUtil.executeSQLQueryList("select * from package_postage_detail_t where conPostageid ="+id+" order by sort",PackagePostageDetailModel.class);
		if(packagePostageDetailModelDetailList==null){
			packagePostageDetailModelDetailList=new ArrayList<>();
		}
		for (PackagePostageDetailModel packagePostageDetailModel : packagePostageDetailModelDetailList) {
			if(packagePostageDetailModel.getMileage()==null){
				packagePostageDetailModel.setMileRadio(2);
			}else {
				packagePostageDetailModel.setMileRadio(1);
			}
		}
		
		packagePostageModel.setPackagePostageDetailModelDetailList(packagePostageDetailModelDetailList);
		
		mv.addObject("packagePostageModel", packagePostageModel);
	}
	@Override
	public void updateStateByIds(String idStr,Integer state) 
	{
		AdminUser adminUser=getLoginUser();
		String hql = "update   package_postage_t set status= ?,operdate=now(),operid="+adminUser.getId()+"  where id in( "+idStr+")";
		HibernateUtil.executeSQLUpdate(hql, state.toString());
		
	}
	

	@Override
	public void updateDelByIds(String idStr) {
		// TODO Auto-generated method stub
		AdminUser adminUser=getLoginUser();
		String hql = "update  package_postage_t set del=1,operdate=now(),operid="+adminUser.getId()+" where id in( ? )";
		HibernateUtil.executeSQLUpdate(hql, idStr);
	}
	
}